package org.game;

import lombok.extern.slf4j.Slf4j;
import org.common.BaseMain;
import org.common.CommonConfig;
import org.common.akka.AkkaContext;
import org.common.dispatcher.ProtoDispatcher;
import org.common.mongo.MongoService;
import org.common.netty.NettyClient;
import org.common.redis.RedisService;
import org.common.utils.ClassScannerUtils;
import org.common.utils.SpringUtils;
import org.game.handler.GameToLoginNettyHandler;
import org.game.obj.RoleData;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Set;

/**
 * @author WeiFan
 */
@Slf4j
@Component
public class GameMain extends BaseMain {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(GameBeanConfig.class);
        applicationContext.start();

        GameMain gameMain = SpringUtils.getBean(GameMain.class);
        gameMain.init();

        System.exit(0);
    }

    @Override
    protected void handleBackGroundCmd(String cmd) {

    }

    @Override
    protected void initServer() {
        CommonConfig commonConfig = SpringUtils.getBean(CommonConfig.class);
        // actor初始化
        AkkaContext.initActorSystem();
        // mongo服务启动
        MongoService mongoService = SpringUtils.getBean(MongoService.class);
        mongoService.initMongoService(commonConfig.getMongoHost(), commonConfig.getMongoUser(), commonConfig.getMongoPassword(), commonConfig.getLoginDbName());
        // redis服务启动
        RedisService redisService = SpringUtils.getBean(RedisService.class);
        redisService.initRedisService(commonConfig.getRedisHost(), commonConfig.getRedisPassword());
        // netty启动, 连接到登录服
        NettyClient nettyClient = SpringUtils.getBean(NettyClient.class);
        String loginInnerHost = commonConfig.getLoginInnerHost();
        nettyClient.start(loginInnerHost, GameToLoginNettyHandler.class);
        try {
            Set<Class<?>> classes = ClassScannerUtils.getClasses("org.game");
            // 协议转发器初始化
            ProtoDispatcher protoDispatcher = SpringUtils.getBean(ProtoDispatcher.class);
            protoDispatcher.load(classes);
            // 注册entityType和entityClass的映射关系
            RoleData.registerEntityTypeAndEntityClass(classes);
        } catch (IOException | URISyntaxException | ClassNotFoundException | NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }
}